package com.chuanyun.wechatcheckin.controller;

import com.chuanyun.wechatcheckin.service.CheckinDataSyncService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.Instant;
import java.time.ZoneId;

/**
 * 打卡数据同步控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/checkin-sync")
@RequiredArgsConstructor
public class CheckinSyncController {

    private final CheckinDataSyncService checkinDataSyncService;

    /**
     * 同步指定日期范围的打卡数据
     * @param startDateParam 开始日期（时间戳格式如1760117014）
     * @param endDateParam 结束日期（时间戳格式如1760203414）
     * @return 同步结果
     */
    @PostMapping("/sync-by-date-range")
    public ResponseEntity<CheckinDataSyncService.CheckinSyncResult> syncByDateRange(
            @RequestParam("startDate") String startDateParam,
            @RequestParam("endDate") String endDateParam) {
        
        log.info("接收到同步打卡数据请求，日期参数: startDate={}, endDate={}", startDateParam, endDateParam);
        
        try {
            // 解析日期参数（支持ISO日期格式和时间戳格式）
            LocalDate startDate = parseDateParameter(startDateParam);
            LocalDate endDate = parseDateParameter(endDateParam);
            
            log.info("解析后的日期范围: {} 到 {}", startDate, endDate);
            CheckinDataSyncService.CheckinSyncResult result = checkinDataSyncService.syncCheckinDataByDateRange(startDate, endDate);
            
            if (result.isSuccess()) {
                log.info("打卡数据同步成功: {}", result);
                return ResponseEntity.ok(result);
            } else {
                log.error("打卡数据同步失败: {}", result);
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            log.error("同步打卡数据时发生异常", e);
            CheckinDataSyncService.CheckinSyncResult errorResult = new CheckinDataSyncService.CheckinSyncResult();
            errorResult.setSuccess(false);
            errorResult.setErrorMessage("系统异常: " + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResult);
        }
    }

    /**
     * 解析日期参数，只支持时间戳格式
     * @param dateParam 日期参数（时间戳格式如"1760117014"）
     * @return LocalDate对象
     * @throws IllegalArgumentException 如果日期格式无效
     */
    private LocalDate parseDateParameter(String dateParam) {
        if (dateParam == null || dateParam.trim().isEmpty()) {
            throw new IllegalArgumentException("日期参数不能为空");
        }
        
        dateParam = dateParam.trim();
        
        try {
            // 解析时间戳格式（秒级时间戳）
            if (dateParam.matches("\\d+")) {
                long timestamp = Long.parseLong(dateParam);
                // 如果是毫秒级时间戳，转换为秒级
                if (timestamp > 9999999999L) {
                    timestamp = timestamp / 1000;
                }
                return Instant.ofEpochSecond(timestamp)
                        .atZone(ZoneId.of("Asia/Shanghai"))
                        .toLocalDate();
            }
            
            throw new IllegalArgumentException("只支持时间戳格式的日期参数: " + dateParam);
            
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("时间戳格式无效: " + dateParam);
        } catch (Exception e) {
            throw new IllegalArgumentException("日期参数解析失败: " + dateParam + ", 错误: " + e.getMessage());
        }
    }

    /**
     * 同步今天的打卡数据
     * @return 同步结果
     */
    @PostMapping("/sync-today")
    public ResponseEntity<CheckinDataSyncService.CheckinSyncResult> syncToday() {
        log.info("接收到同步今天打卡数据请求");
        
        try {
            CheckinDataSyncService.CheckinSyncResult result = checkinDataSyncService.syncTodayCheckinData();
            
            if (result.isSuccess()) {
                log.info("今天打卡数据同步成功: {}", result);
                return ResponseEntity.ok(result);
            } else {
                log.error("今天打卡数据同步失败: {}", result);
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            log.error("同步今天打卡数据时发生异常", e);
            CheckinDataSyncService.CheckinSyncResult errorResult = new CheckinDataSyncService.CheckinSyncResult();
            errorResult.setSuccess(false);
            errorResult.setErrorMessage("系统异常: " + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResult);
        }
    }

    /**
     * 同步最近N天的打卡数据
     * @param days 天数
     * @return 同步结果
     */
    @PostMapping("/sync-recent")
    public ResponseEntity<CheckinDataSyncService.CheckinSyncResult> syncRecent(
            @RequestParam(defaultValue = "7") int days) {
        
        log.info("接收到同步最近{}天打卡数据请求", days);
        
        if (days <= 0 || days > 30) {
            CheckinDataSyncService.CheckinSyncResult errorResult = new CheckinDataSyncService.CheckinSyncResult();
            errorResult.setSuccess(false);
            errorResult.setErrorMessage("天数参数无效，必须在1-30之间");
            return ResponseEntity.badRequest().body(errorResult);
        }
        
        try {
            CheckinDataSyncService.CheckinSyncResult result = checkinDataSyncService.syncRecentCheckinData(days);
            
            if (result.isSuccess()) {
                log.info("最近{}天打卡数据同步成功: {}", days, result);
                return ResponseEntity.ok(result);
            } else {
                log.error("最近{}天打卡数据同步失败: {}", days, result);
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            log.error("同步最近{}天打卡数据时发生异常", days, e);
            CheckinDataSyncService.CheckinSyncResult errorResult = new CheckinDataSyncService.CheckinSyncResult();
            errorResult.setSuccess(false);
            errorResult.setErrorMessage("系统异常: " + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResult);
        }
    }
}